import { handleSql } from 'src/support/untils/sql';
import { CarInfo } from './car_info.entity';
import { FindAllCarInfoDto } from './dto/findAll-car_info.dto';
import { Injectable } from '@nestjs/common';
import { CreateCarInfoDto } from './dto/create-car_info.dto';
import { UpdateCarInfoDto } from './dto/update-car_info.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, In } from 'typeorm';

@Injectable()
export class CarInfoService {
  constructor(
    @InjectRepository(CarInfo)
    private carInfoRepository: Repository<CarInfo>,
  ) {}
  create(createCarInfoDto: CreateCarInfoDto) {
    const entity = this.carInfoRepository.create(createCarInfoDto);
    return this.carInfoRepository.save(entity);
  }

  async findAll(findAllCarInfoDto: FindAllCarInfoDto) {
    const {
      limit = 10,
      page = 1,
      model_id,
      energy,
      tag_types,
      tag,
      ...params
    } = findAllCarInfoDto;
    const where = handleSql(params);
    if (model_id) {
      where['model_id'] = model_id;
    }
    if (energy) {
      where['energy'] = energy;
    }
    const order = {};
    if(tag_types==1){
      order['price'] = 'ASC';
    }else if(tag_types==2){
      order['price'] = 'DESC';
    }else if(tag_types==3){
      order['seating'] = 'ASC';
    }
    if(tag){
      where['tag'] = In(tag.split(','));
    }
    const result = await this.carInfoRepository.findAndCount({
      where: where,
      skip: (page - 1) * limit,
      take: limit,
      order:order
    });

    return {
      list: result[0],
      total: result[1],
    };
  }

  findOne(id: number) {
    return this.carInfoRepository.findOneById(id);
  }

  async update(id: number, updateCarInfoDto: UpdateCarInfoDto) {
    const hasEntriy = await this.carInfoRepository.findOneById(id);
    if (!hasEntriy) {
      return;
    }
    const updateInfo = this.carInfoRepository.merge(
      hasEntriy,
      updateCarInfoDto,
    );
    const result = await this.carInfoRepository.save(updateInfo);
    return result;
  }

  async remove(id: number) {
    const result = await this.carInfoRepository.delete(id);
    return result;
  }

  async getTotal() {
    const result = await this.carInfoRepository.count();
    return result;
  }

  async getListTime(key: string) {
    const result = await this.carInfoRepository.countBy({
      list_time: Like(`%${key}%`),
    });
    return result;
  }
}
